<?php

/**
 * This is the model class for table "product".
 *
 * The followings are the available columns in table 'product':
 * @property integer $product_id
 * @property string $product_name
 * @property string $product_code
 * @property integer $cat_id
 * @property string $cat_code
 * @property integer $image_id
 * @property string $price
 * @property string $currency
 * @property string $location
 * @property integer $buy_method_id
 * @property string $detail
 * @property integer $views
 * @property integer $add_time
 * @property integer $user_id
 * @property string $user_name
 * @property integer $modify_time
 * @property integer $tieubieu
 * @property integer $banchay
 * @property integer $published
 * @property integer $nick_ym
 * @property integer $nick_skype
 * @property integer $website
 * @property integer $activation_code
 * @property integer $status
 */
class Product extends CActiveRecord {
    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'product';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('product_name, product_code, description, cat_id, cat_code,  price, currency, location, buy_method_id, detail, views, add_time, user_id, user_name, modify_time, tieubieu, banchay, published', 'required'),
            array('cat_id,  buy_method_id, views, add_time, user_id, modify_time, tieubieu, banchay, published', 'numerical', 'integerOnly' => true),
            array('product_name, product_code, cat_code, location, user_name', 'length', 'max' => 255),
            array('price', 'length', 'max' => 15),
            array('currency', 'length', 'max' => 20),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('product_id, product_name, product_code, description, cat_id, cat_code, image_id, price, currency, location, buy_method_id, detail, views, add_time, user_id, user_name, modify_time, tieubieu, banchay, published', 'safe', 'on' => 'search'),
            array('product_id,product_name', 'safe', 'on' => 'searchForBackendGrid'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'image' => array(self::BELONGS_TO, 'Image', 'image_id'),
            'buy_method' => array(self::BELONGS_TO, 'BuyMethod', 'buy_method_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'product_id' => 'Product',
            'product_name' => 'Tên',
            'product_code' => 'Product Code',
            'description' => 'Mô tả sản phẩm',
            'cat_id' => 'Danh mục',
            'cat_code' => 'Cat Code',
            'image_id' => 'Hình ảnh',
            'price' => 'Giá',
            'currency' => 'Tiền tệ',
            'location' => 'Khu vực',
            'buy_method_id' => 'Cách thức mua hàng',
            'detail' => 'Chi tiết',
            'views' => 'Lượt xem',
            'add_time' => 'Ngày tạo',
            'user_id' => 'User',
            'user_name' => 'User Name',
            'modify_time' => 'Modify Time',
            'tieubieu' => 'Tiêu biểu',
            'banchay' => 'Bán chạy',
            'published' => 'Cho phép hiển thị',
            'nick_ym' => 'Nick yahoo',
            'nick_skype' => 'Nick skype',
            'website' => 'Website',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search() {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('product_id', $this->product_id);
        $criteria->compare('product_name', $this->product_name, true);
        $criteria->compare('product_code', $this->product_code, true);
        $criteria->compare('description', $this->description, true);
        $criteria->compare('cat_id', $this->cat_id);
        $criteria->compare('cat_code', $this->cat_code, true);
        $criteria->compare('image_id', $this->image_id);
        $criteria->compare('price', $this->price, true);
        $criteria->compare('currency', $this->currency, true);
        $criteria->compare('location', $this->location, true);
        $criteria->compare('buy_method_id', $this->buy_method_id);
        $criteria->compare('detail', $this->detail, true);
        $criteria->compare('views', $this->views);
        $criteria->compare('add_time', $this->add_time);
        $criteria->compare('user_id', $this->user_id);
        $criteria->compare('user_name', $this->user_name, true);
        $criteria->compare('modify_time', $this->modify_time);
        $criteria->compare('tieubieu', $this->tieubieu);
        $criteria->compare('banchay', $this->banchay);
        $criteria->compare('published', $this->published);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Product the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function getPictureHtml() {
        $product = Product::model()->findByPk($this->product_id);
        $url = TreTodayUrl::getPictureUrl($product->image != null ? $product->image->image_path : Yii::app()->params['no-image']);
        if (TreTodayCommon::checkRemoteFile($url)) {
            if ($product->image != null) {
                $size = $this->getRatio($url);
                return '<a href="' . TreTodayUrl::getProductUrl($this->product_id, $this->product_name) . '" ><img style="padding:10px" width="' . $size['width'] . '" height="' . $size['height'] . '" src="' . $url . '"  alt="Rao vặt hot - ' . $this->product_name . '"/></a>';
            } else {
                return '<a href="' . TreTodayUrl::getProductUrl($this->product_id, $this->product_name) . '" ><img style="padding:10px" width="80" height="80" src="' . $url . '" alt="Rao vặt hot - ' . $this->product_name . '"/></a>';
            }
        }
        return '<a href="' . TreTodayUrl::getProductUrl($this->product_id, $this->product_name) . '" ><img style="padding:10px" width="80" height="80" src="' . $url . '"  alt="Rao vặt hot - ' . $this->product_name . '"/></a>';

    }

    public function getRatio($img, $width = 80, $height = 80) {
        $size = getimagesize($img);
        return TreTodayCommon::getResizeImage(80, 80, $width, $height);
//        $size = getimagesize($img);
//        return TreTodayCommon::getResizeImage($size[0], $size[1], $width, $height);
    }

    public function getPictureUrl() {
        $product = Product::model()->findByPk($this->product_id);

        $url = $product->image != null ? TreTodayUrl::home() . $product->image->image_path : '';
        $existed = TreTodayCommon::checkRemoteFile($url);
        $url = $existed ? $url : Yii::app()->params['no-image'];
        return TreTodayUrl::getPictureUrl($url);
    }

    public function getNameHtml() {
        return '<a href="' . TreTodayUrl::getProductUrl($this->product_id, $this->product_name) . '" >' . $this->product_name . '</a>';
    }

    public function getNameHtmlForGrid() {
        return '<a style="display: block;height: inherit;text-align: left;" href="' . TreTodayUrl::getProductUrl($this->product_id, $this->product_name) . '" >' . $this->product_name . '</a>';
    }

    public function getPrice() {
        return TreTodayCommon::formatPrice($this->price, $this->currency);
    }

    public function getLocation() {

        return TreTodayCommon::getLocationName($this->location);
    }

    public function getForGrid($cat_id, $location = 0) {
        $criteria = new CDbCriteria();
        $criteria->select = 'product_id, product_name, price,currency, location';

        if ($location == 0) {
            $criteria->condition = 'cat_id = :cat_id and (published = 1 or status = 1) ';
            $criteria->params = array(':cat_id' => $cat_id);
        } else {
            $criteria->condition = 'cat_id = :cat_id and (published = 1 or status = 1) and location = :location';
            $criteria->params = array(':cat_id' => $cat_id, ':location' => $location);
        }
        $criteria->order = 'product_id DESC';
        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
            'pagination' => array('pageSize' => 10) //Yii::app()->params['backendPageSize']),
        ));
    }

    public function searchForGrid($keyword, $cat_id) {
        $keyword = strtolower(trim($keyword));
        $criteria = new CDbCriteria();
        $criteria->select = 'product_id, product_name, price,currency, location';
        if ($cat_id == 0) {
            $criteria->condition = "LOWER(t.product_name) like '%$keyword%'  and (published = 1 or status = 1)";
            $criteria->params = array(':cat_id' => $cat_id);
        } else {
            $criteria->condition = "LOWER(t.product_name) like '%$keyword%' and cat_id = :cat_id and (published = 1 or status = 1)";
            $criteria->params = array(':cat_id' => $cat_id);
        }
        $criteria->order = 'product_id DESC';
        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
            'pagination' => array('pageSize' => 10) //Yii::app()->params['backendPageSize']),
        ));
    }

    public function  getLatestForGrid($location = 0) {
        $criteria = new CDbCriteria();
        $criteria->select = 'product_id, product_name, price,currency, location';
        if ($location == 0) {
            $criteria->condition = 'published = 1 or status = 1';
        } else {
            $criteria->condition = ' (published = 1 or status = 1) and location = :location';
            $criteria->params = array(':location' => $location);
        }
        $criteria->order = 'product_id DESC';
        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
            'pagination' => array('pageSize' => 10) //Yii::app()->params['backendPageSize']),
        ));
    }

    public function  getForInterested($location = 0, $cat) {

        $criteria = new CDbCriteria();
        $criteria->select = 'product_id, product_name, price,currency, location';
        if ($location == 0 && $cat == '') {
            $criteria->condition = 'published = 1 or status = 1';
        } elseif ($location == 0 && $cat != '') {
            $criteria->condition = '(published = 1 or status = 1) and  cat_id in (:cat_id)';
            $criteria->params = array('cat_id' => $cat);
        } else {
            $criteria->condition = ' (published = 1 or status = 1) and location = :location and  cat_id in (:cat_id)';
            $criteria->params = array(':location' => $location, 'cat_id' => $cat);
        }
        $criteria->order = "product_id DESC";
        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
            'pagination' => array('pageSize' => 10)
        ));
    }

    public function getForGridByUser($user_id) {
        $criteria = new CDbCriteria();
        $criteria->select = 'product_id, product_name, price,currency, location';
        $criteria->condition = 'user_id = :user_id and (published = 1 or status = 1)';
        $criteria->params = array(':user_id' => $user_id);
        $criteria->order = 'product_id DESC';
        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
            'pagination' => array('pageSize' => 10) //Yii::app()->params['backendPageSize']),
        ));
    }

    public function getForGridBackend($published) {
        $criteria = new CDbCriteria;
        $criteria->select = '*';
        $criteria->condition = 'published = :published';
        $criteria->params = array(':published' => $published);

        $criteria->order = 'product_id DESC';

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
            'pagination' => array('pageSize' => Yii::app()->params['backendPageSize']),
        ));
    }

    public function searchForBackendGrid($display = true) {
        $criteria = new CDbCriteria;
        $criteria->select = '*';
        $criteria->compare('product_id', $this->product_id, true);
        $criteria->compare('product_name', $this->product_name, true);
        $criteria->addCondition('published = :published');
        $criteria->params = array_merge($criteria->params, array(':published' => $display));
        $criteria->order = 'product_id DESC';

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
            'pagination' => array('pageSize' => Yii::app()->params['backendPageSize']),
        ));
    }

}
